<template>
    <div>
        <div class="demo-collapse">
            <el-collapse v-model="activeNames" @change="handleChange">
                <el-collapse-item 
                    v-for="(project, index) in ProjectsContributed" 
                    :key="index" 
                    :name="index + 1">
                    <template #title>
                        <h1>项目名称: {{ project.name }} | 个人已捐款: {{ project.totalAmount }}</h1>
                        <router-link :to="{ path:'/projectDetail', query: { id: project.pid }}">
                            <el-icon><Link /></el-icon>
                        </router-link>
                    </template>
                    <div>
                        <ul>
                            <li v-for="(contribution, subIndex) in project.contributions" :key="subIndex">
                                募捐金额: {{ contribution.amount }}, 募捐时间: {{ contribution.time }}
                                <el-button 
                                    @click="handleDelete(contribution.cid)" 
                                    type="danger" 
                                    size="small" 
                                    style="margin-right: 10px;">删除</el-button>
                            </li>
                        </ul>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </div>
    </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';

export default {
    data() {
        return {
            activeNames: [],
            ProjectsContributed: []
        }
    },
    computed: {
        ...mapState('Contribution', ['Contributions']),
    },
    created() {
        this.fetchUserContributions();
    },
    watch: {
        Contributions: {
            handler(newVal) {
                if (newVal.length) {
                    this.aggregateContributions(newVal);
                }
            },
            immediate: true
        }
    },
    methods: {
        ...mapActions('Contribution', ['getUserContributions', 'deleteContribution']),
        ...mapActions('AllProject', ['getProjectByPid']),
        // 获取用户的捐款信息
        async fetchUserContributions() {
            const userId = JSON.parse(localStorage.getItem('User')).userid;
            await this.getUserContributions(userId);
        },
        // 聚合用户的捐款信息
        async aggregateContributions(contributions) {
            const contributionsMap = {};
            for (const contribution of contributions) {
                if (!contributionsMap[contribution.pid]) {
                    contributionsMap[contribution.pid] = {
                        pid: contribution.pid,
                        contributions: [],
                        totalAmount: 0,
                        name: ''
                    };
                }
                contributionsMap[contribution.pid].totalAmount += contribution.amount;
                contributionsMap[contribution.pid].contributions.push({
                    cid: contribution.cid,
                    amount: contribution.amount,
                    time: this.formatDate(contribution.time)
                });
                if (!contributionsMap[contribution.pid].name) {
                    const projectDetail = await this.getProjectByPid(contribution.pid);
                    contributionsMap[contribution.pid].name = projectDetail.name;
                }
            }

            this.ProjectsContributed = Object.values(contributionsMap);
        },
        // 点击删除按钮触发的事件
        async handleDelete(cid) {
            try {
                await this.deleteContribution(cid);
                await this.fetchUserContributions();
            } catch (error) {
                console.error("删除失败:", error);
            }
        },
        // 格式化日期
        formatDate(timestamp) {
            const date = new Date(timestamp);
            return date.toLocaleString();
        }
    }
}
</script>

<style>
/* 如果需要，添加自定义样式 */
</style>
